/*
 * 15-11.c
 *
 *  Created on: 2012-5-14
 *      Author: ncrd
 */


#include "../apue.h"
#include <sys/shm.h>

#define ARRAY_SIZE 40000
#define MALLOC_SIZE 100000
#define SHM_SIZE 1024
#define SHM_MODE 0600

char array[ARRAY_SIZE];
int global_var = 1;
static int static_global_bss_var;
static int static_global_var = 2;

int main (void) {
	int shmid;
	static int static_var = 0;
	static int static_bss_var;
	int *ptr, *shmptr;
	key_t shmkey;
	printf("array[] from %lx to %lx\n", (unsigned long)&array[0], (unsigned long)&array[ARRAY_SIZE]);
	printf("stack around %lx\n", (unsigned long)&shmid);
	printf("global variable around %lx\n", (unsigned long)&global_var);
	printf("static global variable around %lx\n", (unsigned long)&static_global_var);
	printf("static global bss variable around %lx\n", (unsigned long)&static_global_bss_var);
	printf("static variable around %lx\n", (unsigned long)&static_var);
	printf("static bss variable around %lx\n", (unsigned long)&static_bss_var);

	if ((ptr = (int *)malloc(MALLOC_SIZE)) == NULL) err_sys("malloc error");
	printf("malloced from %lx to %lx\n", (unsigned long)ptr, (unsigned long)ptr+MALLOC_SIZE);

	shmkey = ftok("1.c", 0);
	if ((shmid = shmget(shmkey, SHM_SIZE, SHM_MODE|IPC_CREAT)) < 0) err_sys("shmget error");
	if ((shmptr = (int *)shmat(shmid, 0, 0)) == (int *)-1) err_sys("shmat error");
	while (1) {
		sleep(2);
		printf("server before change %d\n", *shmptr);
		*shmptr = 100;
	}
	if (shmdt(shmptr) < 0) err_sys("shmdt error");

	exit(0);
}
